package com.jbh.recordlibrary.u;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.PorterDuff;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import com.google.gson.Gson;
import com.jbh.recordlibrary.i.CallBack;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;


/**
 * Created by zbsdata on 2018/10/20.
 */

public class BitmapUtil {


    /**
     * 将字符串转成bitmap
     *
     * @param context
     * @param keZi
     * @return
     */
    public static Bitmap convertStringToBitmap(Context context,String keZi){
        TextView textView = new TextView(context);
        textView.setTextColor(Color.BLACK);
        textView.setText(keZi);
        textView.setTextSize(14);
        return convertViewToBitmap(textView);
    }


    //view 转bitmap
    public static Bitmap convertViewToBitmap(View view) {
        //设置能否缓存图片信息（drawing cache）
        view.setDrawingCacheEnabled(true);
        view.measure(
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        //如果能够缓存图片，则创建图片缓存
        view.buildDrawingCache();
        Bitmap bitmap = view.getDrawingCache();
//        系统把原来的cache销毁
//        view.setDrawingCacheEnabled(false);
//        释放缓存占用的资源
//        view.destroyDrawingCache();
        return bitmap;
    }


    /**
     * 保存
     *
     *
     * @param activity
     * @param b
     */
    public static Uri saveBitmapToCard(final Context activity, final Bitmap b){
        FileOutputStream outputStream = null;
        try {
            File f=new File( SdcardUtil.getSaveDir(activity)+File.separator+"dering_share");
            if (!f.exists()){
                f.mkdir();
            }

            File file = new File(f.getPath()+File.separator+System.currentTimeMillis()+".png");
            file.createNewFile();
            outputStream = new FileOutputStream(file.getPath());
            b.compress(Bitmap.CompressFormat.PNG,100,outputStream);


            ContentValues values = new ContentValues();
            values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
            values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
            Uri uri = activity.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            activity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));


            return uri;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null ;
    }


    /**
     * 保存
     *
     *
     * @param activity
     * @param b
     */
    public static Uri saveBitmapToCard(final Context activity, final Bitmap b, CallBack<String> callBack){
        FileOutputStream outputStream = null;
        try {
            File f=new File( SdcardUtil.getSaveDir(activity)+File.separator+"share");
            if (!f.exists()){
                f.mkdir();
            }
            File  file = new File(f.getPath()+File.separator+System.currentTimeMillis()+".png");
            file.createNewFile();
            outputStream = new FileOutputStream(file.getPath());
            b.compress(Bitmap.CompressFormat.PNG,100,outputStream);

            ContentValues values = new ContentValues();
            values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
            values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
            Uri uri = activity.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            activity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
            callBack.success(file.getPath());
            return uri;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            callBack.error("保存失败");
        } catch (IOException e) {
            e.printStackTrace();
            callBack.error("保存失败");
        }
        return null ;
    }


    /**
     * @param bitmap
     * @param newWidth
     * @param newHeight
     * @return
     */
    public static Bitmap zoomImage(Bitmap bitmap, double newWidth, double newHeight) {
        // 获取这个图片的宽和高
         float width = bitmap.getWidth();
         float height = bitmap.getHeight();
         // 创建操作图片用的matrix对象
         Matrix matrix = new Matrix();
         // 计算宽高缩放率
         float scaleWidth = ((float) newWidth) / width;
         float scaleHeight = ((float) newHeight) / height;
         // 缩放图片动作
         matrix.postScale(scaleWidth, scaleHeight);
         Bitmap bit = Bitmap.createBitmap(bitmap, 0, 0, (int) width, (int) height, matrix, true);
         return bit;
    }




    /**
     * 是常用canvas将view转成bitmap
     *
     * @param view
     *
     * @return
     * @throws Throwable
     */
    public static Bitmap captureView(View view){
        Bitmap bm = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
        bm.setHasAlpha(true);
        Canvas canvas = new Canvas(bm);
        canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
        view.draw(canvas);
        return bm;
    }




    /**
     * view转成bitmap的方法在之一
     *
     * @param view
     * @return
     */
    public static Bitmap getViewToBitmap(View view){
        //设置能否缓存图片信息（drawing cache）
        view.setDrawingCacheEnabled(true);
        //如果能够缓存图片，则创建图片缓存
        view.buildDrawingCache();
        //调用getDrawingCache方法就可 以获得view的cache图片
        Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
//        系统把原来的cache销毁
        view.setDrawingCacheEnabled(false);
//        释放缓存占用的资源
        view.destroyDrawingCache();
//        MediaStore.Images.Media.insertImage(MyApplication.getContext().getContentResolver(),bitmap,"","");
        return bitmap;
    }





    /**
     * 得到bitmap的大小
     */
    public static int getBitmapSize(Bitmap bitmap) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {    //API 19
            return bitmap.getAllocationByteCount();
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {//API 12
            return bitmap.getByteCount();
        }
        // 在低版本中用一行的字节x高度
        return bitmap.getRowBytes() * bitmap.getHeight(); //earlier version
    }





    /**
     * 指定区域裁切图片
     */
    public static Bitmap ImageCrop(Bitmap bitmap,Rect rect) {
        try {
            Log.v("======b========","scrollX="+new Gson().toJson(rect));
            return Bitmap.createBitmap(bitmap, rect.left, rect.top, rect.right-rect.left, rect.bottom-rect.top,null,false);
        }catch (IllegalArgumentException e){
            e.printStackTrace();
        }
        //下面这句是关键
        return null;
    }





    /**
     * 质量压缩方法
     *
     * @param image
     * @return
     */
    public static Bitmap compressImage(Bitmap image) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.PNG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 90;
        while (baos.toByteArray().length / 1024 > 500) { // 循环判断如果压缩后图片是否大于500kb,大于继续压缩
            baos.reset(); // 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.PNG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;// 每次都减少10
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
        return bitmap;
    }





    /**
     * 转换文件大小
     *
     * @return
     */
    public static String FormetFileSize(long s) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        if (s < 1024) {
            fileSizeString = df.format((double) s) + "B";
        } else if (s < 1048576) {
            fileSizeString = df.format((double) s / 1024) + "K";
        } else if (s < 1073741824) {
            fileSizeString = df.format((double) s / 1048576) + "M";
        } else {
            fileSizeString = df.format((double) s / 1073741824) + "G";
        }
        return fileSizeString;
    }




    /**
     * 缩放bitmap
     *
     * @param bitmap
     * @return
     */
    public static Bitmap scaleBitmap(Bitmap bitmap,int newWidth,int newHeight){
        int height = bitmap.getHeight();
        int width = bitmap.getWidth();

        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;

        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);// 使用后乘
        Bitmap newBM = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, false);

//      if (!bitmap.isRecycled()){
//            bitmap.recycle();
//        }

        return  newBM;
    }






    /**
     * 缩放bitmap
     *
     * @param bitmap
     * @return
     */
    public static Bitmap scaleBitmap(Bitmap bitmap,float radio){
        int height = bitmap.getHeight();
        int width = bitmap.getWidth();
        Matrix matrix = new Matrix();
        matrix.postScale(radio, radio);// 使用后乘
        Bitmap newBM = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, false);
        return  newBM;
    }


    /**
     * 等比 缩放
     *
     * @param w
     * @param bitmap
     * @return
     */
    public static Bitmap getScaleBitmap(float w,Bitmap bitmap){
        Bitmap b = null ;
        try {
            int width = bitmap.getWidth();
            int height = bitmap.getHeight();
            Matrix matrix=new Matrix();
            if (width>0&&height>0){
                float scale = (float) (w*1.0/width);
                matrix.postScale(scale,scale);
                b = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, false);
            }else {
                b = null ;
            }
        }catch (IllegalArgumentException e){
            e.printStackTrace();
            b = null ;
        }
        return b;
    }

}
